import router from '@/router'
import config from '@/config'
//系统顶部tabs标签栏记录
export default {
	state:{
		tabs:[],
		cacheList:[],
		activeTab:'',
	},
	mutations:{
		addTab(state,tab){
			if(tab.matched.length<2)return
			var hasOne=state.tabs.findIndex(item=>item.name==tab.name)
			state.activeTab=tab.name
			if(hasOne==-1&&!tab.meta.isHome&&tab.path!='/'&&tab.name!=config.baseRouteName){
				state.tabs.push(tab)
				if(tab.meta.nocache==true)return
				state.cacheList.push(tab.name)
			}
		},
		removeTab(state,tabName){
			var index=state.tabs.findIndex(item=>item.name==tabName)
			state.cacheList=state.cacheList.filter(item=>item!=tabName)
			router.replace({
				name:tabName,
			})
			setTimeout(() => {
				state.tabs=state.tabs.filter(item=>item.name!==tabName)
				if(state.tabs.length==0){
					router.replace('/')
				}else if(index<=state.tabs.length-1){
					router.replace({
						name:state.tabs[index].name,
						query:state.tabs[index].query,
						params:state.tabs[index].params,
					})
				}else{
					router.replace({
						name:state.tabs[index-1].name,
						query:state.tabs[index-1].query,
						params:state.tabs[index-1].params,
					})
				}
			}, 10);


		},
		closeAll(state){
			state.tabs=[]
			state.cacheList=[]
			router.replace({
				name:config.baseRouteName,
			})
		},
		closeOther(state,tabName){
			var index=state.tabs.findIndex(item=>item.name==tabName)
			var route=state.tabs[index]
			state.tabs=[route]
			state.cacheList=[route.name]
			router.replace({
				name:route.name,
				query:route.query,
				params:route.params,
			})
		},
		setActive(state,tabName){
			var index=state.tabs.findIndex(item=>item.name==tabName)
			var route=state.tabs[index]
			router.replace({
				name:route.name,
				query:route.query,
				params:route.params,
			})
		},
		updateTabs(state,tabs){
			state.tabs=tabs
		},
		refreshTo(state,tabName){
			var index=state.tabs.findIndex(item=>item.name==tabName)
			if(index>-1){
				state.cacheList=state.cacheList.filter(item=>item!=tabName)
				router.replace({
					name:tabName,
				})
				setTimeout(() => {
					var route=state.tabs[index]
					router.replace({
						name:route.name,
						query:route.query,
						params:route.params,
					})
				}, 10);
			}else{
				router.replace({
					name:tabName,
				})
			}
		},
	},
}
